package com.myblog.demo.common;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * 头像处理工具类
 */
public class PhotoTools {

    public static boolean isImage(MultipartFile file) {
        String contentType = file.getContentType();
        return contentType != null &&
                (contentType.equals("image/jpeg") || contentType.equals("image/png"));
    }
    public static boolean isImageSizeValid(MultipartFile file, long maxSize) {
        return file.getSize() <= maxSize;
    }

    public static String generateUniqueFileName(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename != null ?
                originalFilename.substring(originalFilename.lastIndexOf(".")) :
                "";
        return UUID.randomUUID().toString() + extension;
    }

    public static boolean saveImage(MultipartFile file, String filePath, String fileName) {
        try {
            System.out.println(filePath);
            File dest = new File(filePath + fileName);
            file.transferTo(dest);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}
